import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import { Spider } from "@/ipc/spider.ts";
import { MirrorDataFilter } from "@/modules/dev-env/mirror/filter.ts";
import type { DefaultOptionType } from "ant-design-vue/es/vc-select/Select";
import type { GenericFileInfo } from "@common/spider-types.ts";

class GolangTypeFilter extends MirrorDataFilter {
  constructor() {
    super("版本类型", "stable");
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.edition === this.value);
  }

  protected getDataSource0(): Promise<DefaultOptionType[]> {
    return Promise.resolve([
      { value: "stable", label: "稳定版本" },
      { value: "test", label: "测试版" },
      { value: "history", label: "历史版本" },
    ]);
  }
}

export class GolangBitnessFilter extends MirrorDataFilter {
  constructor() {
    super("位数", 64);
  }

  protected filter0(versions: ToolInstallVersionItem[]): ToolInstallVersionItem[] {
    return versions.filter(it => it.bitness === this.value);
  }

  protected getDataSource0(): Promise<DefaultOptionType[]> {
    return Promise.resolve([
      { value: 64, label: "64位" },
      { value: 32, label: "32位" },
    ]);
  }
}

export abstract class GolangMirror extends BaseEnvMirror {
  protected getFilters0(): MirrorDataFilter[] {
    return [new GolangTypeFilter(), new GolangBitnessFilter()];
  }

  async getDownloadList(query: Record<string, any>): Promise<ToolInstallVersionItem[]> {
    const fileList = await Spider.getGolangDownloadList(this.url);
    return fileList.map<ToolInstallVersionItem>(it => ({
      id: `go-${it.version}-${it.bitness}`,
      name: it.name,
      version: it.version,
      url: this.getDownloadUrl(it),
      bitness: it.bitness,
      size: it.size,
      edition: it.type,
    }));
  }

  protected getDownloadUrl(info: GenericFileInfo) {
    return info.url;
  }
}

export class GolangGoDevCnMirror extends GolangMirror {
  // https://dl.google.com/go/go1.25rc2.windows-amd64.zip

  private readonly _downloadPrefix = "https://go.dev/dl";
  private readonly _replacedPrefix = "https://dl.google.com/go";

  constructor() {
    super({
      id: "golang.godev",
      name: "go.dev",
      url: "https://go.dev",
      website: "https://go.dev/",
    });
  }

  protected getDownloadUrl(info: GenericFileInfo): string {
    return info.url.replace(this._downloadPrefix, this._replacedPrefix);
  }
}

export class GolangGoogleCnMirror extends GolangMirror {
  constructor() {
    super({
      id: "golang.google",
      name: "golang.google.cn",
      url: "https://golang.google.cn",
      website: "https://golang.google.cn/",
    });
  }
}
